package com.blue.blog.api.service.impl;

import com.blue.blog.api.mapper.UserMapper;
import com.blue.blog.api.pojo.User;
import com.blue.blog.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {
    @Autowired
    private UserMapper mapper;

    @Autowired
    private PasswordEncoder encoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = mapper.findUserByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在!");
        }

        return user;
    }

    @Override
    public List<User> findAllUser() {
        List<User> users = mapper.findAllUser();

        for (User user : users) {
            user.setPassword("");
        }

        return users;
    }

    @Override
    public User findUserByUsername(String username) {
        User user = mapper.findUserByUsername(username);
        if (user != null) {
            user.setPassword("");
        }

        return user;
    }

    @Override
    public User findUserByEmail(String email) {
        User user = mapper.findUserByEmail(email);
        if (user != null) {
            user.setPassword("");
        }

        return user;
    }

    @Override
    public Integer saveUser(User user) {
        // 前端出入的 Password 需要后端经过加密后存储到数据库中
        user.setPassword(encoder.encode(user.getPassword()));

        return mapper.saveUser(user);
    }

    @Override
    public Integer updateUser(User user) {
        return mapper.updateUser(user);
    }

    @Override
    public Integer deleteUserById(Long id) {
        return mapper.deleteUserById(id);
    }
}
